package com.oedtech.esl.controller.security;

import com.alibaba.fastjson.JSONObject;
import com.oedtech.esl.controller.BaseController;
import com.oedtech.esl.json.JsonResult;
import com.oedtech.esl.model.sys.Store;
import com.oedtech.esl.repository.sys.StoreDao;
import com.oedtech.esl.repository.sys.UserDao;
import com.oedtech.esl.service.securityService.StoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.io.IOException;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;

@RequestMapping("/store_rest")
@RestController
public class StoreRestController extends BaseController{

    @Autowired
    private StoreDao storeDao;
    @Autowired
    private UserDao userDao;

    @Autowired
    private StoreService storeService;





    @PostMapping("/add_change_store")
    public JsonResult AddOrChangeStore(@RequestBody Store store){

        try {
            return storeService.addOrChangeStore(store);
        } catch (IOException e) {
            return new JsonResult("error", e.getMessage());
        }
    }


    @PostMapping("/change_password")
    public JsonResult changePwd(String storeCode,String password,Principal principal){
        if(storeCode==null)return new JsonResult("error","门店不存在");
        if(password==null||password.length()<6)return new JsonResult("error","密码不能小于6位");
        password=new BCryptPasswordEncoder().encode(password);
        if(storeDao.changePassword(password,storeCode,principal.getName())>0){
            return new JsonResult("success",null);
        }
        return new JsonResult("error","操作失败");
    }


    @RequestMapping("/delete_store")
    public void deleteStore(@RequestParam(name = "storeId")String storeCode){

        storeService.deleteStore(storeCode);
    }


    @PostMapping("/addBsIdRelate")
    public JsonResult addBsIdRelate(@RequestBody JSONObject jo,Principal principal){
        if(jo.get("bsId")==null||jo.get("storeCode")==null){
            logger.warn("add ap relate fail:parameters can not null");
            return new JsonResult("error","缺少必要参数");
        }
        String bsId=jo.getString("bsId");
        String storeCode=jo.getString("storeCode");
        try{
        return storeService.relateBsid(bsId,storeCode,principal.getName());
    }catch (Exception e){
        logger.error("add ap relate fail",e);
        return new JsonResult("error",e.getMessage());
    }

    }

    @PostMapping("/deleteBsidRelate")
    public JsonResult deleteBsidRelate(@RequestBody JSONObject jo,Principal principal){
        if(jo.get("bsid")==null||jo.get("storeCode")==null){
            logger.warn("delete ap relate fail:parameters can not null");
            return new JsonResult("error","缺少必要参数");
        }
        return storeService.deleteRelate( principal.getName(), jo.getString("storeCode"),jo.getString("bsid"));
    }
    //商品列表分页查询
    @RequestMapping("/listByPage")
    public Page<Store> listByPage(int page, int size, String sortStr, boolean sortAscOrDesc, String searchObj, Principal principal) {

        Integer sourceFlag = userDao.findSourceFlagByUsername(principal.getName());
        Specification<Store> specification = getSpecification(searchObj,sourceFlag);

        if (StringUtils.isEmpty(sortStr)) {
            return storeDao.findAll(specification, PageRequest.of(page,size));
        } else {
            return storeDao.findAll(specification, PageRequest.of(page, size, new Sort((sortAscOrDesc ? Sort.Direction.ASC : Sort.Direction.DESC), sortStr)));
        }
    }
    private Specification getSpecification(String searchObj,Integer sourceFlag)
    {
        JSONObject search =JSONObject.parseObject(searchObj);

        Specification<Store> specification = new Specification<Store>()
        {
            @Override
            public Predicate toPredicate(Root<Store> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder)
            {
                List<Predicate> queryList = new ArrayList<Predicate>();
                if(sourceFlag!=0){
                    queryList.add(criteriaBuilder.equal(root.get("sourceFlag"), sourceFlag));
                }

                if (search.get("storeCode") != null && !StringUtils.isEmpty(search.get("storeCode") + ""))
                {
                    queryList.add(criteriaBuilder.like(root.get("storeCode"), "%"+search.get("storeCode") + "%"));
                }
                if (search.get("storeName") != null && !StringUtils.isEmpty(search.get("storeName") + ""))
                {
                    queryList.add(criteriaBuilder.like(root.get("storeName"), "%"+search.get("storeName") + "%"));
                }
                if (search.get("sourceFlag") != null && !StringUtils.isEmpty(search.get("sourceFlag") + ""))
                {
                    queryList.add(criteriaBuilder.equal(root.get("sourceFlag"), search.get("sourceFlag")));
                }
                if (queryList.size() > 0)
                {
                    criteriaQuery.where(criteriaBuilder.and(queryList.toArray(new Predicate[queryList.size()])));
                }

                return criteriaQuery.getRestriction();
            }
        };

        return specification;
    }

}
